import warnings
import time
import subprocess
from paddleocr import PaddleOCR
from PIL import Image, ImageDraw
import configparser

warnings.filterwarnings("ignore")

# 定义装饰器,用于测时间开销
def time_calc(func):
    def wrapper(*args, **kargs):
        start_time = time.time()
        f = func(*args, **kargs)
        exec_time = time.time() - start_time
        print("func.name:{}\texec_time:{}".format(func.__name__, exec_time))
        return f
    return wrapper

# 点击
def adb_tap(x, y):
    command = [adb_path, 'shell', 'input', 'tap', str(x), str(y)]
    try:
        result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print(f"Clicked at coordinates: ({x}, {y})")
    except subprocess.CalledProcessError as e:
        print(f"Failed to tap: {e.stderr.decode().strip()}")


def ocr_return_to_success():
    print("--------------------",ocr_return_to_success_num[0],ocr_return_to_success_num[1],ocr_return_to_success_num[2],ocr_return_to_success_num[3])
    crop_screenshot('screen.png', 'screen1.png', (ocr_return_to_success_num[0],ocr_return_to_success_num[1],ocr_return_to_success_num[2],ocr_return_to_success_num[3]))
    text = ocr.ocr("screen1.png", cls=True)
    print(text)

    if text == [None]:
        return

    length = len(text[0])
    if length in [0,1,4,5,6,7]:
        adb_tap(开心收下_x, 开心收下_y)
        time.sleep(0.2)
        adb_tap(继续1_x, 继续1_y)
        time.sleep(0.2)
        adb_tap(继续2_x, 继续2_y)
        return 0

    if text[0][1][1][0][0] in ["胜","生"]:
        return 0

    if "场" in text[0][1][1][0]:
        return 0

    if text[0][0][1][0] in ["?","？.","？","?."]:
        return 0


    if text[0][1][1][0] not in  ["?","？.","？","?."]:
        print(f'num1:{text[0][0][1][0]}\nnum2:{text[0][1][1][0]}')
        num1 = text[0][0][1][0]
        num2 = text[0][1][1][0]

    elif text[0][1][1][0] in ["?","？.","？","?."]:
        if length == 2:
            num1 = 0
            num2 = 0
        if length == 3:
            print(f'num1:{text[0][0][1][0]}\nnum2:{text[0][2][1][0]}')
            num1 = text[0][0][1][0]
            num2 = text[0][2][1][0]
    else:
        num1 = "0.0"
        num2 = "0.0"
    num1 = str(num1)
    num2 = str(num2)
    num1 = num1.replace("L","1")
    num2 = num2.replace("L","1")
    num1 = num1.replace("V", "20")
    num2 = num2.replace("V", "20")
    num1 = num1.replace("N", "8")
    num2 = num2.replace("n", "12")
    num1 = num1.replace("n", "12")
    num2 = num2.replace("N", "8")
    num1 = num1.replace("O", "0")
    num2 = num2.replace("O", "0")
    num1 = num1.replace(".", "")
    num2 = num2.replace(".", "")
    try:

        num1 = float(num1)
        num2 = float(num2)
    except:
        num1 = 1
        num2 = 2
    print(num1)

    print(num2)
    if num1>num2:
        suc = ">"
        # 大于符号
        swipe(880, 1650, 100, 1450)
        swipe(880, 1650, 100, 1750)

    elif num1<num2:
        suc = "<"
        # 小于符号
        swipe(880, 1450, 100, 1650)
        swipe(100, 1650, 880, 1750)
    else:
        suc = "="
        # 等于符号
        swipe(100, 1450, 880, 1450)
        swipe(100, 1750, 880, 1750)
    time.sleep(0.28)
    print(f'{num1}{suc}{num2}')
    # for i in text[0]:
    #     num1 = i[1][0]
    #     if i[1][0] in ["?","？"]:


# 绘制展示图片
def drew_init_img(input_path,output_path,xy_arr):
    image = Image.open(input_path)

    # 创建一个 ImageDraw 对象用于在图片上绘图
    draw = ImageDraw.Draw(image)

    for i in xy_arr:
        # print(i)
        draw.rectangle(i, outline="red", width=5)


    # 保存为新图片
    image.save(output_path)

    # 如果你想展示一下图片
    image.show()

# 滑动操作
def swipe(x1, y1, x2, y2, duration=2):
    command = [adb_path, 'shell', 'input', 'swipe', str(x1), str(y1), str(x2), str(y2), str(duration)]
    result = subprocess.run(command)
    if result.returncode == 0:
        pass
        # print(f"Swiped from ({x1}, {y1}) to ({x2}, {y2}) in {duration} ms")
    else:
        print("Failed to swipe")

# 保存屏幕截图
@time_calc
def capture_screenshot(output_file='screen.png'):
    # 使用 ADB 的完整路径
    command = [adb_path, 'exec-out', 'screencap', '-p']
    with open(output_file, 'wb') as f:
        # 运行 ADB 命令并保存截图到文件
        result = subprocess.run(command, stdout=f)
    if result.returncode == 0:
        ocr_return_to_success()

    else:
        pass
        print("Failed to capture screenshot")

# 裁剪截图
def crop_screenshot(input_file, output_file, crop_area):
    """
    裁剪截图中的特定区域
    :param input_file: 输入的完整屏幕截图文件路径
    :param output_file: 输出的裁剪后图片文件路径
    :param crop_area: 裁剪区域 (left, top, right, bottom)
    """
    try:
        with Image.open(input_file) as img:
            cropped_img = img.crop(crop_area)
            cropped_img.save(output_file)

            # print(f"Cropped screenshot saved to {output_file}")
    except Exception as e:
        print(f"Failed to crop screenshot: {e}")

# 只截图
def adb_img(file_path:str):
    adb_img_result_command = [adb_path, 'exec-out', 'screencap', '-p']
    with open(file_path, 'wb') as adb_img_result_command_f:
        adb_img_result = subprocess.run(adb_img_result_command, stdout=adb_img_result_command_f)
    if adb_img_result.returncode == 0:
        print(f"保存成功,保存文件名为：{file_path}")
        return True
    else:
        return False

# 获取手机分辨率
def get_screen_resolution():
    # 执行 adb shell wm size 命令
    result = subprocess.run(['adb', 'shell', 'wm', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

    # 检查命令是否成功执行
    if result.returncode == 0:
        # 输出示例："Physical size: 1080x2400"
        output = result.stdout.strip()
        # 解析出分辨率
        if 'Physical size' in output:
            resolution = output.split(":")[1].strip()
            x, y= resolution.split("x")
            return x,y
        else:
            return "无法获取分辨率信息"
    else:
        return f"命令执行失败: {result.stderr}"



if __name__ == '__main__':
    # ocr 坐标是顺时针 去左上和右下就是数组index=>0和2
    # 设置不同手机适配坐标录入
    ocr = PaddleOCR(use_angle_cls=True, use_gpu=True)
    adb_path = r'D:\PycharmProjects\abd_suse\platform-tools-latest-windows\platform-tools\adb.exe'
    # 相关参数
    ocr_return_to_success_num = []
    开心收下_x = 0
    开心收下_y = 0
    继续1_x = 0
    继续1_y = 0
    继续2_x = 0
    继续2_y = 0
    # 更改配置文件
    conf = configparser.ConfigParser()
    filename = "./config/conf.ini"
    conf.read(filename)
    if conf.get("phone","jx2_y") == '0':
        # 按要求打开手机页面执行程序
        print("欢迎使用，请按要求打开规定页面，打开后请键入  init 即可开始初始化")
        # 键入再进行
        if input("请键入 任意键回车 开始第一步"):
            # if input() == "init":
            # 运行 ADB 命令并保存截图到文件
            if adb_img("init1.png"):
                init_button = ocr.ocr("init1.png", cls=True)
                print(init_button)
                drew_xy = []
                Questions = []
                for i in init_button[0]:

                    left_top = [int(x) for x in i[0][0]]
                    left_top = tuple(left_top)
                    right_bottom = [int(x) for x in i[0][2]]
                    right_bottom = tuple(right_bottom)
                    text = i[1][0]
                    odds = i[1][1]

                    if any(s in text for s in ["?", "？"]):
                        Questions.append([left_top, right_bottom])
                    print(left_top)  # 左上
                    print(right_bottom)  # 右下
                    print(text)  # 识别文字
                    print(odds)  # 可能性
                    drew_xy.append([left_top, right_bottom])

                drew_init_img("init1.png", "init_drew1.png", drew_xy)
                # 调用函数并打印分辨率
                screen_w, screen_h = get_screen_resolution()
                conf['phone']['crop0'] = str(50)
                conf['phone']['crop1'] = str(Questions[0][0][0] - 50)
                conf['phone']['crop2'] = str(int(screen_w) - 50)
                conf['phone']['crop3'] = str(Questions[0][1][1] + 50)
                ocr_return_to_success_num = [50, Questions[0][0][1] - 50, int(screen_w) - 50, Questions[0][1][1] + 50]
                conf['phone']['width_max'] = screen_w
                conf['phone']['height_max'] = screen_h
                print(f"手机分辨率: {screen_w}x{screen_h}")
                if len(Questions) != 1 and len(Questions) != 2:
                    print("屏幕中出现多个非题目的？,?问好字符，请排查去掉非题目中问好字符，避免影响ocr判断")
                    exit(0)
                elif len(Questions) == 1:
                    question1_left_top, question1_right_bottom = Questions[0]
                elif len(Questions) == 2:
                    question1_left_top, question1_right_bottom = Questions[0]
                print("请完成本次进行进入下一个规定页面")
                if input("请键入 任意键回车 进行下一步"):
                    if adb_img("init2.png"):
                        init_button = ocr.ocr("init2.png", cls=True)
                        print(init_button)
                        for i in init_button[0]:
                            left_top = [int(x) for x in i[0][0]]
                            right_bottom = [int(x) for x in i[0][2]]
                            text = i[1][0]
                            odds = i[1][1]
                            if any(s in text for s in ["开心收下"]):

                                x = (left_top[0] + right_bottom[0]) // 2
                                y = (left_top[1] + right_bottom[1]) // 2
                                开心收下_x = x
                                开心收下_y = y
                                conf['phone']['kxsx_x'] = str(x)
                                conf['phone']['kxsx_y'] = str(y)
                                print(x, y)
                                adb_tap(x, y)
                                time.sleep(1)

                                if adb_img("init3.png"):
                                    init_button = ocr.ocr("init3.png", cls=True)
                                    print(init_button)
                                    for i in init_button[0]:
                                        left_top = [int(x) for x in i[0][0]]
                                        right_bottom = [int(x) for x in i[0][2]]
                                        text = i[1][0]
                                        odds = i[1][1]
                                        if any(s in text for s in ["继续"]):
                                            x = (left_top[0] + right_bottom[0]) // 2
                                            y = (left_top[1] + right_bottom[1]) // 2
                                            继续1_x = x
                                            继续1_y = y
                                            conf['phone']['jx1_x'] = str(x)
                                            conf['phone']['jx1_y'] = str(y)
                                            print(x, y)
                                            adb_tap(x, y)
                                            time.sleep(1)

                                            if adb_img("init4.png"):
                                                init_button = ocr.ocr("init4.png", cls=True)
                                                print(init_button)
                                                for i in init_button[0]:
                                                    left_top = [int(x) for x in i[0][0]]
                                                    right_bottom = [int(x) for x in i[0][2]]
                                                    text = i[1][0]
                                                    odds = i[1][1]
                                                    if any(s in text for s in ["继续", "再练一次"]):
                                                        x = (left_top[0] + right_bottom[0]) // 2
                                                        y = (left_top[1] + right_bottom[1]) // 2
                                                        继续_x2 = x
                                                        继续_y2 = y
                                                        conf['phone']['jx2_x'] = str(x)
                                                        conf['phone']['jx2_y'] = str(y)
                                                        print(x, y)
                                                        adb_tap(x, y)
                                                        time.sleep(1)
                                                        with open(filename, 'w') as configfile:
                                                            conf.write(configfile)

                                break
    else:
        conf.get("phone","jx2_y")
        ocr_return_to_success_num = []
        ocr_return_to_success_num.append(int(conf.get("phone", "crop0")))
        ocr_return_to_success_num.append(int(conf.get("phone", "crop1")))
        ocr_return_to_success_num.append(int(conf.get("phone", "crop2")))
        ocr_return_to_success_num.append(int(conf.get("phone", "crop3")))
        开心收下_x = int(conf.get("phone","kxsx_x"))
        开心收下_y = int(conf.get("phone","kxsx_y"))
        继续1_x = int(conf.get("phone","jx1_x"))
        继续1_y = int(conf.get("phone","jx1_y"))
        继续2_x = int(conf.get("phone","jx2_x"))
        继续2_y = int(conf.get("phone","jx2_y"))
        while True:
            isopen = input("是否开始：输入任意键开始，q退出程序")
            if isopen == 'q':
                break
            else:
                for i in range(15):
                    capture_screenshot('screen.png')





    print("程序结束")









